package com.mini.cn.goods.observer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mini.cn.goods.action.ActionProxy;
import com.mini.cn.goods.action.BaseAction;
import com.mini.cn.goods.action.Gift;
import com.mini.cn.goods.common.observes.IObserver;
import com.mini.cn.goods.common.observes.Message;
import com.mini.cn.goods.common.observes.TheadPool;
import com.mini.cn.goods.common.observes.YaKashMessageManager;
import com.mini.cn.goods.config.BaseConfig;
import com.mini.cn.goods.config.MessageConfig;
import com.mini.cn.goods.io.netty.ws.info.FastPushMsg;
import com.mini.cn.goods.observer.message.PayMessage;
import com.mini.cn.goods.po.*;
import com.mini.cn.goods.po.dto.GroupGoods;
import com.mini.cn.goods.po.dto.OrderDto;
import com.mini.cn.goods.service.*;
import com.mini.cn.goods.servlet.GoodsDataDicManager;
import com.mini.cn.goods.servlet.ws.common.LCServiceConfig;
import com.mini.cn.goods.servlet.ws.common.ResponseMap;
import com.mini.cn.goods.servlet.ws.service.IPushResultCallback;
import com.mini.cn.goods.servlet.ws.service.IPushService;
import com.mini.cn.goods.util.SendTempUtil;
import com.mini.cn.goods.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.UUID;


/**
 * Created by fly on 17/7/10.
 */
@Component("payob")
@Slf4j
public class PayMessageObserver implements IObserver {

    @Autowired
    ActionProxy actionProxy;

    @Autowired
    UserService userService;

    @Autowired
    TemplateService templateService;

    @Autowired
    AppService appService;

    @Autowired
    UserAddressService userAddressService;

    @Autowired
    GoodsDataDicManager goodsDataDicManager;

    @Autowired
    VipService vipService;

    @Autowired
    UserBuyLogService userBuyLogService;

    @Autowired
    IPushService pushService;

    @Autowired
    IPushResultCallback pushResultCallback;


    @PostConstruct
    public void init() {
        YaKashMessageManager.INSTANCE.registerMessage(String.valueOf(MessageConfig.PAYSUCESS), this);
        log.info("init payMessageObserver");
    }

    //  how  validate the  destory method is  a question
    @PreDestroy
    public void cleanUp() {
        YaKashMessageManager.INSTANCE.unRegisterMessage(String.valueOf(MessageConfig.PAYSUCESS), this);
        log.info("cleanUp");
    }


    public void onNoticeMessage(Message message) {
        log.info("PayMessageObserver onNoticeMessage come in");
        final PayMessage payMessage = (PayMessage) message;
        final OrderInfo orderInfo = payMessage.order;
        final UserInfo userInfo = payMessage.userInfo;
        //发放奖励
        TheadPool.sendGiftThreadPoolExecutor.submit(new Runnable() {

            public void run() {
                try {
                    BaseAction action = actionProxy.createRealAction(BaseConfig.COMSUMEACTION, userInfo, orderInfo);
                    List<Gift> gifts = actionProxy.findActionGift(action);
                    if (gifts != null && gifts.size() > 0) {
                        log.info("gift=" + gifts);
                        actionProxy.giveGift(action, gifts);
                    }
                } catch (Exception e) {

                }
            }
        });

        //用户vip等级计算 生成采购信息入库
        TheadPool.messageObserverWorkhreadPoolExecutor.submit(new Runnable() {
            public void run() {
                //总消费金额
                try {
                    //用户采购信息入库
                    String goodslist = orderInfo.getcCoffeelist();
                    JSONArray goodsArray = JSONArray.parseArray(goodslist);
                    for (int i = 0; i < goodsArray.size(); i++) {
                        JSONObject goodsObject = goodsArray.getJSONObject(i);
                        String goodid = goodsObject.getString("goodsId");
                        Integer count = goodsObject.getInteger("count");
                        for (int j = 0; j < count; j++) {
                            Userbuylog userbuylog = new Userbuylog();
                            userbuylog.setcAppid(orderInfo.getcAppid());
                            userbuylog.setcGoodsid(goodid);
                            userbuylog.setcOpenid(orderInfo.getcOpenid());
                            userBuyLogService.save(userbuylog);
                        }
                    }
                    //用户附件商品入库
                    int appid = orderInfo.getcAppid();
                    //用户总消费和购买商品数
                    String totalprice = userInfo.getcMonetary();
                    long totalcount = userBuyLogService.findBuyCount(userInfo.getcOpenid(), appid);
                    //当前等级
                    int vid = userInfo.getcVid();
                    String lastPrice = userInfo.getcLastVmonetary();
                    int lastcount = userInfo.getcLastCount();
                    //当前等级
                    Vip vip = vipService.getVip(appid, vid);
                    double cumprice = Double.valueOf(totalprice) - Double.valueOf(lastPrice);
                    long cumcount = totalcount - lastcount;
                    if (vip != null && vip.getcRemark() != null) {
                        //当前等级title
                        VipTitle currvipTitle = JSONObject.parseObject(vip.getcRemark(), VipTitle.class);
                        String currprice = currvipTitle.getPrice();
                        int curbuycount = currvipTitle.getBuycount();
                        List<VipTitle> vipTitles = goodsDataDicManager.getVips(appid);
                        if (vipTitles != null && vipTitles.size() > 0) {
                            for (VipTitle vipTitle : vipTitles) {
                                int rank = vipTitle.getRank();
                                if (rank > vid) {
                                    //判断用户是否升级
                                    String price = vipTitle.getPrice();
                                    if (price == null || price.equals("")) {
                                        price = "0";
                                    }
                                    int paycount = vipTitle.getBuycount();
                                    //得到升级条件
                                    double gleverprice = Double.valueOf(price) - Double.valueOf(currprice);
                                    int glevercount = paycount - curbuycount;
                                    if (cumprice >= gleverprice && cumcount >= glevercount) {
                                        //更新用户vip等级
                                        //更新用户信息
                                        userInfo.setcVid(rank);
                                        userInfo.setcVtime(TimeUtil.getCurrDay(0));
                                        userInfo.setcLastCount((int) totalcount);
                                        userInfo.setcLastVmonetary(totalprice);
                                        userService.update(userInfo);
                                        break;

                                    }
                                }
                            }
                        }
                    }

                    //发送信息模版
                    App app = appService.findAppById(orderInfo.getcAppid());
                    Useraddress useraddress = userAddressService.findAddressById(userInfo.getcOpenid(), userInfo.getcAppid(), orderInfo.getcAddrid());
                    if (app != null && useraddress != null) {
                        Template template = templateService.findTemplateByappidAndType(app.getcAppid(), BaseConfig.TEMPLATEORDER);
                        SendTempUtil.sendOrderTemp(orderInfo, template, useraddress, app.getcNotifyOpenid());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //发送接龙信息
        byte pay = orderInfo.getcPayway();
        if ((byte) 2 == pay) {
            FastPushMsg fastPushMsg = new FastPushMsg();
            fastPushMsg.setMsgId(UUID.randomUUID().toString());
            fastPushMsg.setMsgSceneId(String.format(LCServiceConfig.MsgSceneId.PAYSUCCESS, userInfo.getcAppid()));
            fastPushMsg.setCommand(LCServiceConfig.LCServiceCmd.FASTPUSH_TYPE);
            ResponseMap map = new ResponseMap();

            OrderDto orderDto = new OrderDto();
            String list = orderInfo.getcCoffeelist();
            List<GroupGoods> goods = JSONArray.parseArray(list, GroupGoods.class);
            orderDto.setGoodsList(goods);
            try {
                UserModel userModel = userService.findUserByOpenId(orderInfo.getcOpenid(), orderInfo.getcAppid());
                orderDto.setUserName(userModel.userInfo.getcName());
                orderDto.setAppId(orderInfo.getcAppid());
                orderDto.setUserLogo(userModel.userInfo.getcLogo());
                long ctime = orderInfo.getcCtime().getTime();
                orderDto.setCTime(ctime);
                map.setData(orderDto);
                fastPushMsg.setMsgBody(map);
                //推送发送接龙信息
                pushService.pushAllUserFastUnpack(fastPushMsg, pushResultCallback);
                App app = appService.findAppById(orderInfo.getcAppid());
                //发送模版信息
                Template template = templateService.
                        findTemplateByappidAndType(String.valueOf(app.getcAppid()), BaseConfig.TEMPLATEGROUP);
                if (null == template) {
                    return;
                }
                SendTempUtil.sendGroupOrderTemp(orderInfo, template, app.getcNotifyOpenid(), app.getcMchid());
            } catch (Exception e) {
                log.error("push is error", e);
            }
        }
    }

    @Override
    public String getObserverName() {
        return "payob";
    }
}
